const TOKEN_KEY = 'child_app_token'
const USER_INFO_KEY = 'child_app_user_info'

export const getToken = () => {
  return localStorage.getItem(TOKEN_KEY)
}

export const setToken = (token: string) => {
  localStorage.setItem(TOKEN_KEY, token)
}

export const removeToken = () => {
  localStorage.removeItem(TOKEN_KEY)
}

export const getUserInfo = () => {
  const userInfo = localStorage.getItem(USER_INFO_KEY)
  return userInfo ? JSON.parse(userInfo) : null
}

export const setUserInfo = (userInfo: any) => {
  localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfo))
}

export const removeUserInfo = () => {
  localStorage.removeItem(USER_INFO_KEY)
}

export const clearAuth = () => {
  removeToken()
  removeUserInfo()
}

// 监听主应用的认证同步
if (window.__POWERED_BY_WUJIE__) {
  window.$wujie?.bus.$on('main-app:auth-sync', (data: any) => {
    if (data.type === 'token') {
      if (data.token) {
        console.log('data.token', data.token)
        setToken(data.token)
      } else {
        removeToken()
      }
    } else if (data.type === 'userInfo') {
      if (data.userInfo) {
        setUserInfo(data.userInfo)
      } else {
        removeUserInfo()
      }
    }
  })
} 